var btnid = null
var imgSrc
$.ajax({
    url: "homepage/findTags",
    type: "POST",
    async:false,
    success: function(response) {
        $(".tags-container").empty()
        for (var i = 0; i < response.data.length; i++){
            $(".tags-container").append(`<div class="tag" id="${response.data[i].id}">${response.data[i].tagName}</div>`)
        }
    }
})
// 推荐数量选择
document.querySelectorAll('.count-option').forEach(option => {
    option.addEventListener('click', function() {
        document.querySelectorAll('.count-option').forEach(opt => {
            opt.classList.remove('selected');
        });
        this.classList.add('selected');
    });
});

// 标签选择
document.addEventListener('DOMContentLoaded', function() {
    // 重新绑定标签点击事件
    document.querySelectorAll('.tag').forEach(tag => {
        tag.addEventListener('click', function() {
            console.log('标签被点击了'); // 添加日志确认点击事件触发
            this.classList.add('selected')
        });
    });
});

// 生成推荐路线按钮
document.querySelector('.btn-primary').addEventListener('click', function() {
    const theme = document.querySelector('.theme-input').value;
    const desc = document.querySelector('.theme-desc').value;
    const count = document.querySelector('.count-option.selected').textContent;

    if (!theme) {
        alert('请输入探店主题');
        return;
    }
    let title = $(".theme-input").val()
    // 获取所有选中标签的文本内容数组
    var selectedTags = $('.tags-container .tag.selected').map(function() {
        return $(this).text();
    }).get();
    var ids = $('.tags-container .tag.selected').map(function() {
        return $(this).attr("id");
    }).get();
    ids = ids.join(",")
    selectedTags = selectedTags.join("、")
    console.log(selectedTags);
    console.log(title,desc,count)

    // 模拟加载
    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 生成中...';

    $.ajax({
        url: "exploreScript/add",
        type: "POST",
        async: false,
        data: {
            title: title,
            desc: desc,
            count: count,
            theme: selectedTags,
            username:$.cookie("username"),
            img:imgSrc,
            ids:ids
        },
        success: function(data) {
            console.log(data)
            showRecommendationRoute(data.data)
            setTimeout(() => {
                this.innerHTML = '生成推荐路线';
                alert(`已根据"${theme}"生成了${count}店铺的推荐路线`);
            }, 1500);
        },
    })


});
document.getElementById('coverUpload').addEventListener('click', function() {
    document.getElementById('coverInput').click();
});
function handleCoverUpload(input) {
    const file = input.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('coverImage').src = e.target.result;
            document.getElementById('coverPreview').style.display = 'block';
            document.getElementById('coverUpload').style.display = 'none';
        }
        reader.readAsDataURL(file);
    }
}

function showRecommendationRoute(scriptDataArray) {
    const routeSteps = document.getElementById('routeSteps');
    const recommendationSection = document.getElementById('recommendationSection');

    routeSteps.innerHTML = '';

    // 清空现有内容后重新生成
    scriptDataArray.forEach((scriptData, index) => {
        console.log(scriptData)
        // 创建剧本卡片
        const scriptCard = document.createElement('div');
        scriptCard.className = 'script-card';
        scriptCard.innerHTML = `
            <div class="script-header">
                <div class="script-cover">
                    <img src="${scriptData.coverImageUrl}" alt="${scriptData.title}" onerror="this.src='default-cover.jpg'">
                </div>
                <div class="script-info">
                    <h3 class="script-title">${scriptData.title}</h3>
                    <div class="script-theme">${scriptData.theme}</div>
                    <div class="script-meta">
                        <span class="script-author">by ${scriptData.username}</span>
                        <span class="script-stats">
                            <i class="fas fa-eye"></i> ${scriptData.viewCount}
                            <i class="fas fa-heart"></i> ${scriptData.likeCount}
                            <i class="fas fa-play-circle"></i> ${scriptData.usedCount}
                        </span>
                    </div>
                </div>
            </div>
            <div class="script-description">${scriptData.description}</div>
            <div class="script-shops">
                <div class="shops-header">
                    <h4>推荐店铺路线</h4>
                    <div class="route-stats">
                        <div class="stat-item">
                            <i class="fas fa-walking"></i>
                            <span>全程约${Math.round(JSON.parse(scriptData.shopOrder || '[]').length * 0.5)}km</span>
                        </div>
                        <div class="stat-item">
                            <i class="fas fa-clock"></i>
                            <span>预计${JSON.parse(scriptData.shopOrder || '[]').length * 40}分钟</span>
                        </div>
                        <div class="stat-item">
                            <i class="fas fa-store"></i>
                            <span>${JSON.parse(scriptData.shopOrder || '[]').length}家店铺</span>
                        </div>
                    </div>
                </div>
                <div class="shop-list" id="shopList-${scriptData.id}">
                    <!-- 店铺列表将通过JavaScript动态生成 -->
                </div>
            </div>
            <div class="script-actions">
                <button class="route-btn route-start" onclick="startExploration(${scriptData.id})">
                    <i class="fas fa-play"></i>开始探店
                </button>
                <button class="route-btn route-save" onclick="saveScript(${scriptData.id})">
                    <i class="fas fa-bookmark"></i>保存路线
                </button>
                <button class="route-btn route-share" onclick="shareScript(${scriptData.id})">
                    <i class="fas fa-share-alt"></i>分享
                </button>
            </div>
        `;

        routeSteps.appendChild(scriptCard);
    });

    // 显示推荐路线区域
    recommendationSection.style.display = 'block';

    // 滚动到推荐路线区域
    recommendationSection.scrollIntoView({
        behavior: 'smooth'
    });
}
// 清空选择按钮
document.querySelector('.btn-secondary').addEventListener('click', function() {
    document.querySelector('.theme-input').value = '';
    document.querySelector('.theme-desc').value = '';

    document.querySelectorAll('.count-option').forEach(opt => {
        opt.classList.remove('selected');
    });

    document.querySelectorAll('.tag').forEach(tag => {
        tag.classList.remove('selected');
    });

    // 默认选择5家
    document.querySelectorAll('.count-option')[1].classList.add('selected');
});

function initEchartsChinaMap() {
    // 1. 获取地图容器并初始化ECharts实例
    const chartDom = document.getElementById("shopMap");
    const myChart = echarts.init(chartDom);
    const popup = document.getElementById("shopPopup");
    const closePopupBtn = document.getElementById("closePopup");

    // 3. 从数据库获取店铺数据
    $.ajax({
        url: "recommendation/findShopById",
        type: "post",
        data:{
            id:btnid
        },
        async:false,
        success: function(response) {
            if (response.code === 200 && response.data) {
                const shopsData = response.data;

                // 处理店铺数据
                const shopPoints = shopsData.map(shop => {
                    // 处理经纬度数据
                    let longitude = shop.longitude ? parseFloat(shop.longitude) : null;
                    let latitude = shop.latitude ? parseFloat(shop.latitude) : null;

                    // 如果没有经纬度数据，使用默认坐标（北京）
                    if (!longitude || !latitude) {
                        longitude = 116.4042 + (Math.random() - 0.5) * 10;
                        latitude = 39.9153 + (Math.random() - 0.5) * 8;
                    }

                    // 处理评分数据
                    const rating = shop.rating ? parseFloat(shop.rating) : 0;

                    // 判断是否是当前位置（这里需要根据业务逻辑判断）
                    // 假设当前位置的ID为1，或者根据其他条件判断
                    const isCurrentLocation = false; // 根据实际情况修改这个条件


                    var symbolSize = 14;
                    var color = "#ff6b6b"; // 红色 - 其他位置


                    return {
                        id: shop.id,
                        name: shop.name,
                        value: [longitude, latitude],
                        rating: rating,
                        desc: shop.description || '暂无描述',
                        avatar_url: shop.avatarUrl,
                        open_time: shop.openTime || '09:00:00',
                        close_time: shop.closeTime || '18:00:00',
                        rating_count: shop.ratingCount || 0,
                        symbolSize: symbolSize,
                        itemStyle: {
                            color: color
                        },
                        isCurrentLocation: true, // 添加标记
                        label: {
                            show: isCurrentLocation || rating >= 4.0, // 当前位置和评分较高的店铺显示名称
                            formatter: function(params) {
                                return isCurrentLocation ? '当前位置' : shop.name;
                            },
                            position: 'top',
                            color: '#fff',
                            backgroundColor: isCurrentLocation ? '#4e54c8' : 'rgba(0,0,0,0.7)',
                            padding: [2, 4],
                            borderRadius: 4,
                            fontSize: 10
                        }
                    };
                });
                // 添加当前位置到店铺数据中
                const currentLocationPoint = {
                    id: 'current_location',
                    name: '我的位置',
                    value: [longitude, latitude],
                    rating: 5,
                    desc: '当前位置',
                    avatar_url: null,
                    open_time: '全天',
                    close_time: '全天',
                    rating_count: 0,
                    symbolSize: 20,
                    itemStyle: {
                        color: "#4e54c8"
                    },
                    isCurrentLocation: false,
                    label: {
                        show: true,
                        formatter: '我的位置',
                        position: 'top',
                        color: '#fff',
                        backgroundColor: '#4e54c8',
                        padding: [4, 8],
                        borderRadius: 4,
                        fontSize: 12,
                        fontWeight: 'bold'
                    }
                };

                shopPoints.push(currentLocationPoint);
                console.log(shopPoints)


                // 4. 加载中国地图数据
                fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('地图数据加载失败');
                        }
                        return response.json();
                    })
                    .then(chinaJson => {
                        // 注册地图
                        echarts.registerMap('china', chinaJson);

                        // 5. 设置ECharts配置项
                        const option = {
                            backgroundColor: "#f8f9fa",
                            title: {
                                text: `全国店铺分布 (${shopPoints.length -1}家)`,
                                left: "center",
                                textStyle: {
                                    color: "#212529",
                                    fontSize: 16,
                                    fontWeight: "600"
                                }

                            },
                            tooltip: {
                                trigger: "item",
                                backgroundColor: "rgba(255, 255, 255, 0.95)",
                                borderColor: "#e9ecef",
                                borderWidth: 1,
                                textStyle: {
                                    color: "#212529"
                                },
                                formatter: function(params) {
                                    if (params.seriesType === "scatter") {
                                        const shop = params.data;
                                        const stars = '★'.repeat(Math.floor(shop.rating)) + '☆'.repeat(5 - Math.floor(shop.rating));
                                        const locationBadge = shop.isCurrentLocation ?
                                            '<span style="background: #4e54c8; color: white; padding: 2px 6px; border-radius: 10px; font-size: 10px; margin-left: 8px;">当前位置</span>' : '';

                                        return `
                                            <div style="padding: 12px; min-width: 200px;">
                                                <div style="display: flex; align-items: center; margin-bottom: 8px;">
                                                    ${shop.avatar_url ?
                                            `<img src="${shop.avatar_url}" style="width: 40px; height: 40px; border-radius: 8px; margin-right: 8px; object-fit: cover;">` :
                                            `<div style="width: 40px; height: 40px; border-radius: 8px; margin-right: 8px; background: ${shop.isCurrentLocation ? '#4e54c8' : '#ff6b6b'}; display: flex; align-items: center; justify-content: center; color: white;">
                                                            <i class="fas fa-store"></i>
                                                        </div>`
                                        }
                                                    <div style="flex: 1;">
                                                        <div style="display: flex; align-items: center;">
                                                            <h4 style="margin: 0; color: ${shop.isCurrentLocation ? '#4e54c8' : '#ff6b6b'}; font-size: 14px;">${shop.name}</h4>
                                                            ${locationBadge}
                                                        </div>
                                                        <div style="color: #f8961e; font-size: 12px;">${stars} ${shop.rating}</div>
                                                    </div>
                                                </div>
                                                <p style="margin: 4px 0; color: #495057; font-size: 12px;">${shop.desc}</p>
                                                <p style="margin: 4px 0; color: #6c757d; font-size: 11px;">
                                                    <i class="fas fa-clock"></i> ${shop.open_time} - ${shop.close_time}
                                                </p>
                                                <p style="margin: 4px 0; color: #6c757d; font-size: 11px;">
                                                    <i class="fas fa-star"></i> ${shop.rating_count} 条评价
                                                </p>
                                            </div>
                                        `;
                                    }
                                    return params.name;
                                }
                            },
                            visualMap: {
                                show: true,
                                type: "piecewise",
                                pieces: [
                                    { min: 4.5, label: '优秀 (4.5+)', color: "#ff6b6b" },
                                    { min: 4.0, max: 4.4, label: '良好 (4.0-4.4)', color: "#4895ef" },
                                    { min: 3.0, max: 3.9, label: '一般 (3.0-3.9)', color: "#7209b7" },
                                    { max: 2.9, label: '待改善 (<3.0)', color: "#adb5bd" }
                                ],
                                left: "left",
                                top: "bottom",
                                textStyle: {
                                    color: "#495057",
                                    fontSize: 11
                                },
                                itemWidth: 12,
                                itemHeight: 12,
                                borderColor: "#e9ecef"
                            },
                            geo: {
                                map: "china",
                                roam: true,
                                center: [105.0, 36.0],
                                zoom: 1.2,
                                label: {
                                    show: true,
                                    color: "#495057",
                                    fontSize: 10,
                                    fontWeight: "normal"
                                },
                                emphasis: {
                                    label: {
                                        color: "#4361ee",
                                        fontSize: 11,
                                        fontWeight: "bold"
                                    },
                                    itemStyle: {
                                        areaColor: "#e3f2fd",
                                        borderColor: "#4361ee",
                                        borderWidth: 1
                                    }
                                },
                                itemStyle: {
                                    areaColor: "rgba(67, 97, 238, 0.05)",
                                    borderColor: "rgba(67, 97, 238, 0.3)",
                                    borderWidth: 0.5
                                }
                            },
                            series: [
                                // 当前位置标记（蓝色）
                                {
                                    id: "currentLocation",
                                    name: "当前位置",
                                    type: "scatter",
                                    coordinateSystem: "geo",
                                    zlevel: 5, // 更高层级，确保显示在最前面
                                    symbol: "circle",
                                    data: shopPoints.filter(shop => shop.isCurrentLocation),
                                    symbolSize: 20,
                                    itemStyle: {
                                        color: "#4e54c8"
                                    },
                                    emphasis: {
                                        itemStyle: {
                                            shadowBlur: 15,
                                            shadowColor: 'rgba(78, 84, 200, 0.8)',
                                            borderColor: '#4e54c8',
                                            borderWidth: 3
                                        },
                                        label: {
                                            show: true,
                                            fontWeight: 'bold',
                                            backgroundColor: '#4e54c8'
                                        }
                                    },
                                    label: {
                                        show: true,
                                        formatter: '当前位置',
                                        position: 'top',
                                        color: '#fff',
                                        backgroundColor: '#4e54c8',
                                        padding: [4, 8],
                                        borderRadius: 4,
                                        fontSize: 12,
                                        fontWeight: 'bold'
                                    }
                                },
                                // 其他店铺标记（红色）
                                {
                                    id: "otherShops",
                                    name: "其他店铺",
                                    type: "scatter",
                                    coordinateSystem: "geo",
                                    zlevel: 4,
                                    symbol: "circle",
                                    data: shopPoints.filter(shop => !shop.isCurrentLocation),
                                    symbolSize: 14,
                                    itemStyle: {
                                        color: "#ff6b6b"
                                    },
                                    emphasis: {
                                        itemStyle: {
                                            shadowBlur: 10,
                                            shadowColor: 'rgba(255, 107, 107, 0.5)',
                                            borderColor: '#ff6b6b',
                                            borderWidth: 2
                                        },
                                        label: {
                                            show: true,
                                            fontWeight: 'bold'
                                        }
                                    },
                                    label: {
                                        show: true,
                                        formatter: '{b}',
                                        position: 'top',
                                        color: '#fff',
                                        backgroundColor: 'rgba(0,0,0,0.7)',
                                        padding: [2, 4],
                                        borderRadius: 4,
                                        fontSize: 10
                                    }
                                }
                            ],
                            legend: {
                                show: true,
                                orient: 'horizontal',
                                left: 'center',
                                top: 30,
                                data: ['当前位置', '其他店铺'],
                                textStyle: {
                                    color: '#495057',
                                    fontSize: 12
                                }
                            }
                        };

                        // 6. 渲染地图
                        myChart.setOption(option);

                        // // 7. 添加点击事件处理
                        // myChart.on('click', function(params) {
                        //     if (params.seriesType === "scatter") {
                        //         const shop = params.data;
                        //         showShopPopup(shop, params.event.event);
                        //     }
                        // });

                        // 8. 添加控制功能
                        setupControls(myChart);
                    })
                    .catch(error => {
                        console.error('加载地图数据失败:', error);
                        // 可以在这里添加错误处理，比如显示错误信息
                    });
            }
        },
        error: function(xhr, status, error) {
            console.error('获取店铺数据失败:', error);
            // 可以在这里添加错误处理
        }
    });

    // 显示店铺详情弹窗
    function showShopPopup(shopData, event) {
        const popup = document.getElementById("shopPopup");

        // 更新弹窗内容
        document.getElementById("popupTitle").textContent = shopData.name;
        document.getElementById("popupRating").textContent = shopData.rating;
        document.getElementById("popupLocation").textContent = `经度: ${shopData.value[0].toFixed(4)}, 纬度: ${shopData.value[1].toFixed(4)}`;
        document.getElementById("popupType").textContent = shopData.desc || '暂无描述';

        // 设置弹窗标题颜色
        const popupTitle = document.getElementById("popupTitle");
        popupTitle.style.color = shopData.isCurrentLocation ? "#4e54c8" : "#ff6b6b";

        // 先显示弹窗以获取实际尺寸
        popup.style.display = 'block';
        popup.style.visibility = 'hidden';

        // 获取弹窗的实际尺寸
        const popupRect = popup.getBoundingClientRect();
        const popupWidth = popupRect.width;
        const popupHeight = popupRect.height;

        // 恢复可见性
        popup.style.visibility = 'visible';

        // 获取点击位置
        const clickX = event.clientX;
        const clickY = event.clientY;

        // 获取视口尺寸和滚动位置
        const windowWidth = window.innerWidth;
        const windowHeight = window.innerHeight;
        const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
        const scrollY = window.pageYOffset || document.documentElement.scrollTop;

        // 计算绝对位置
        let absoluteX = clickX + scrollX;
        let absoluteY = clickY + scrollY;

        // 智能定位算法
        let finalX, finalY;

        // 水平定位策略
        const spaceRight = windowWidth - clickX - 20;
        const spaceLeft = clickX - 20;

        if (spaceRight >= popupWidth || spaceRight >= spaceLeft) {
            finalX = absoluteX + 15;
        } else {
            finalX = absoluteX - popupWidth - 15;
        }

        // 垂直定位策略
        const spaceBelow = windowHeight - clickY - 20;
        const spaceAbove = clickY - 20;

        if (spaceBelow >= popupHeight || spaceBelow >= spaceAbove) {
            finalY = absoluteY + 15;
        } else {
            finalY = absoluteY - popupHeight - 15;
        }

        // 边界检查
        finalX = Math.max(10, Math.min(finalX, scrollX + windowWidth - popupWidth - 10));
        finalY = Math.max(10, Math.min(finalY, scrollY + windowHeight - popupHeight - 10));

        // 应用位置
        popup.style.position = 'fixed';
        popup.style.left = finalX + 'px';
        popup.style.top = finalY + 'px';
        popup.style.zIndex = '10000';

        // 添加动画效果
        popup.style.opacity = '0';
        popup.style.transform = 'translateY(-10px) scale(0.95)';

        requestAnimationFrame(() => {
            popup.style.transition = 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
            popup.style.opacity = '1';
            popup.style.transform = 'translateY(0) scale(1)';
        });

        // 点击外部关闭
        const closeOnOutsideClick = (e) => {
            if (!popup.contains(e.target)) {
                popup.style.display = 'none';
                document.removeEventListener('click', closeOnOutsideClick);
            }
        };

        setTimeout(() => {
            document.addEventListener('click', closeOnOutsideClick);
        }, 100);
    }

    // 设置控制功能
    function setupControls(myChart) {
        window.addEventListener("resize", function() {
            myChart.resize();
        });
    }
}

// 页面加载完成后初始化地图
document.addEventListener('DOMContentLoaded', function() {
    // 先获取当前位置，然后初始化地图
    var longitude1 = $.cookie("longitude")
    var latitude1 = $.cookie("latitude")
    // 先获取当前位置，然后初始化地图
    getAddressFromKnownCoordinates(longitude1, latitude1)
        .then(addressInfo => {
            console.log('完整地址:', addressInfo.fullAddress);
            console.log('省份:', addressInfo.province);
            console.log('城市:', addressInfo.city);
            console.log('区域:', addressInfo.district);
            longitude = longitude1
            latitude = latitude1
            $("#locationText").html(addressInfo.province+" "+addressInfo.city+" "+addressInfo.district)
            initEchartsChinaMap(longitude1, latitude1,btnid);
        })

});
function getCurrentLocation() {
    return new Promise((resolve, reject) => {
        // 检查浏览器是否支持Geolocation API
        if (!navigator.geolocation) {
            reject(new Error('您的浏览器不支持地理位置功能'));
            return;
        }

        // 获取当前位置
        navigator.geolocation.getCurrentPosition(
            // 成功回调
            (position) => {
                const latitude = position.coords.latitude;  // 纬度
                const longitude = position.coords.longitude; // 经度
                const accuracy = position.coords.accuracy;   // 精度（米）

                resolve({
                    latitude: latitude,
                    longitude: longitude,
                    accuracy: accuracy,
                    timestamp: position.timestamp
                });
            },
            // 错误回调
            (error) => {
                let errorMessage;
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        errorMessage = '用户拒绝提供地理位置权限';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMessage = '无法获取当前位置信息';
                        break;
                    case error.TIMEOUT:
                        errorMessage = '获取位置信息超时';
                        break;
                    default:
                        errorMessage = '发生未知错误';
                        break;
                }
                reject(new Error(errorMessage));
            },
            // 选项配置
            {
                enableHighAccuracy: true,    // 高精度模式
                timeout: 10000,              // 超时时间（10秒）
                maximumAge: 60000            // 缓存位置的最大年龄（60秒）
            }
        );
    });
}
function getAddressFromKnownCoordinates(longitude, latitude) {
    return new Promise((resolve, reject) => {
        const apiKey = '2105ba620f46e78a74b47d937077308a';
        const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude},${latitude}&output=JSON`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.status === '1' && data.regeocode) {
                    const addressComponent = data.regeocode.addressComponent;
                    resolve({
                        fullAddress: data.regeocode.formatted_address,
                        province: addressComponent.province,
                        city: addressComponent.city || addressComponent.province,
                        district: addressComponent.district,
                        township: addressComponent.township,
                        street: addressComponent.streetNumber?.street || '',
                        streetNumber: addressComponent.streetNumber?.number || '',
                        citycode: addressComponent.citycode,
                        adcode: addressComponent.adcode
                    });
                } else {
                    reject(new Error('获取地址信息失败: ' + (data.info || '未知错误')));
                }
            })
            .catch(error => {
                reject(error);
            });
    });
}

$("#coverInput").on("change", function(e) {
    const formData = new FormData();
    formData.append("file", $("#coverInput")[0].files[0]);
    $.ajax({
        url: "/upload",  // 替换为你的Servlet URL
        type: "POST",
        data: formData,
        processData: false,      // 禁止jQuery处理数据（文件上传必须）
        contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
        cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
        success: function (response) {
            imgSrc = response.data
            console.log(imgSrc)
            document.getElementById('coverImage').src=imgSrc
        },error: function(xhr, status, error) {
            console.error("上传失败:", error);
            $("#result").html("上传失败: " + (xhr.responseText || error));
        }
    });
})
